<!-- 提交订单 -->
<template>
  <div
    class="index-container order-index-container"
    :class="is_weixn() ? 'wx-index-container' : ''"
  >
    <div class="goods-detail-box">
      <div>
        <van-image
          :src="state.Img01"
          fit="cover"
          width="100"
          height="100"
          radius="100"
        />
        <div class="goods-detail">
          <h3>开通会员，享永久免费设计</h3>
          <p>{{ amount / 100 }}</p>
        </div>
      </div>
    </div>
    <div class="image-list">
      <van-row :gutter="[5, 5]">
        <van-col span="5" v-for="item in imageList" :key="item">
          <div class="img-item">
            <van-image :src="item" fit="cover" radius="6" />
          </div>
        </van-col>
        <van-col span="4">
          <div class="img-item-more">···</div>
        </van-col>
      </van-row>
    </div>
    <div class="default-browser" v-if="isWxPay">
      <img src="@/assets/image/img08.png" alt="" />
    </div>
    <!-- <van-submit-bar :price="amount" button-text="提交订单" tip="寄送至：湖北 武汉 武昌, 吴先生" :loading="isLoading" -->
    <van-submit-bar
      :price="amount"
      button-text="立即支付"
      :loading="isLoading"
      tip="订单为线上产品，请谨慎购买"
      class="btn-color"
      @submit="payOrder"
    />
  </div>
</template>
<script setup>
import { computed, reactive, toRefs, ref, onMounted } from "vue";
import { appid, wwwUrl } from "@/utils/constant";
import { useRoute, useRouter } from "vue-router";
import { showToast } from "vant";
import {
  CreateGoodsOrder, // 新增订单
  GoodsDetail, // 商品详情
} from "@/api/goods/index.js";

import {
  GetOrderInfoByTradeNo,
  GetOpenid,
  CreatePayOrder,
} from "@/api/mine/index.js";

import { getLocalStorage } from "@/utils/tool";

const route = useRoute();
const router = useRouter();

const checked = ref("1");

const state = reactive({
  Img01: "",
  anchorType: [
    {
      id: 1,
      title: "vip永久更新",
      image: "",
      checked: true,
      money: 0.1,
      context: "元",
    },
  ],
  orderNumber: "", // 订单编号
  isOrder: false,
  isWeixin: false,
});

let isLoading = ref(false);
let setIntTime = null;
let orderNum = "";
let isPay = false;
let isWxPay = ref(false);

const initWeixinJSBridge = () => {
  if (typeof WeixinJSBridge === "object") {
  } else {
    // 微信JSBridge不存在，监听微信JSBridgeReady事件
    document.addEventListener("WeixinJSBridgeReady", () => {}, false);
  }
};

// 拉起微信支付
const onBridgeReady = (pay_info) => {
  console.log(WeixinJSBridge, "WeixinJSBridge222");
  if (WeixinJSBridge !== null) {
    WeixinJSBridge.invoke(
      "getBrandWCPayRequest",
      {
        appId: pay_info.appId, //appid
        timeStamp: pay_info.timeStamp, //时间戳，自1970年以来的秒数
        nonceStr: pay_info.nonceStr, //随机串
        package: pay_info.package,
        signType: pay_info.signType, //微信签名方式：
        paySign: pay_info.paySign, //微信签名
      },
      function (res) {
        console.log("====>: onBridgeReady -> res", res, pay_info);
        if (res.err_msg == "get_brand_wcpay_request:ok") {
          isLoading.value = false
          router.push({
            path: "/payResult",
            query: {
              out_trade_no: pay_info.out_trade_no,
            },
          });

          // 使用以上方式判断前端返回,微信团队郑重提示：
          //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
        } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
          isLoading.value = false
          showToast("用户已取消");
        } else {
        }
      }
    );
  } else {
    console.log("不是在微信app内");
  }
};

const payOrder = async () => {
  if (is_weixn()) {
    let params = {
      openid: localStorage.getItem("openid"),
      goodsId: route.query.goodsId,
      orderType:0
    };
    isLoading.value = true
    let { data } = await CreatePayOrder(params);
    console.log(params, "params", data);
    let pay_info = {
      appId: data.appId, //appid
      timeStamp: data.timeStamp, //时间戳，自1970年以来的秒数
      nonceStr: data.nonceStr, //随机串
      package: data.package,
      signType: data.signType, //微信签名方式：
      paySign: data.paySign, //微信签名
      out_trade_no: data.out_trade_no, //微信签名
    };
    onBridgeReady(pay_info);
  } else {
    alipay();
  }
  //
};

const alipay = async () => {
  orderNum = "";
  isPay = false;
  let paramsorder = {
    goodsId: route.query.goodsId,
    orderType: 0,
  };
  isLoading.value = true;
  let datares = await CreateGoodsOrder(paramsorder);
  let resData = datares.data;
  isLoading.value = false;
  document.getElementById("payMent").innerHTML = resData;
  let namevalue = document.getElementsByName("biz_content")[0].value;
  orderNum = JSON.parse(namevalue);
  localStorage.setItem("out_trade_no", orderNum.out_trade_no);
  document.forms[0].setAttribute("target", "_self"); // 当前窗口跳转
  document.forms[0].submit();
  document.getElementById("payMent").innerHTML = "";
};

const getPayResult = async () => {
  let trade_no = localStorage.getItem("out_trade_no");
  let params = {
    orderId: trade_no,
  };
  let { data } = await GetOrderInfoByTradeNo(params);
  try {
    clearInterval(setIntTime);
    if (data.order_status == 1) {
      router.push({
        path: "/register",
        query: {  
          id: data.token,
        },
      });
    }
    if (data.order_status == 0 && isPay) {
      showToast("当前订单未支付");
    }
  } catch (error) {
    clearInterval(setIntTime);
  }
};

// 提交支付
let isPopup = ref(false);
const submitPay = () => {
  // payOrder()
  isPopup.value = true;
};

const is_weixn = () => {
  var ua = navigator.userAgent.toLowerCase();
  if (ua.match(/MicroMessenger/i) == "micromessenger") {
    return true;
  } else {
    return false;
  }
};

const getOpenidFn = async () => {
  //先判断有没有授权(判断地址栏code，有就-用户同意了授权，没有-没授权或者拒绝授权)
  // let str = route.query.code; //此处使用的是history路由模式，hash这么拿不到。
  let _params = queryURLParams(window.location.href);
  if (_params.code) {
    // 走后端接口(把code传给后台，让后台根据code获取openID与用户信息)
    let params = {
      code: _params.code,
    };
    // setIsPageLoading(true)
    let data = await GetOpenid(params);
    console.log(data, "a");
    if (data.openid) {
      localStorage.setItem("openid", data.openid);
      //拿到了ACCESS_TOKEN与用户openid，跳转到登录页面
      let jspParams = {
        url: window.location.href,
      };
      console.log(jspParams, "jspParams");
      try {
        let dataJsp = await getJspToken(jspParams);
        wx.config({
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: appid, // 必填，公众号的唯一标识
          timestamp: dataJsp.data.timestamp, // 必填，生成签名的时间戳
          nonceStr: dataJsp.data.nonceStr, // 必填，生成签名的随机串
          signature: dataJsp.data.signature, // 必填，签名
          jsApiList: ["checkJsApi", "chooseWXPay"], // 必填，需要使用的JS接口列表
        });
        wx.ready(function (res) {
          wx.checkJsApi({
            jsApiList: ["chooseWXPay"],
            success: (res) => {
              console.log("checked api:", res);
            },
            fail: (err) => {
              console.log("check api fail:", err);
            },
          });
          // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
        });
        return;
      } catch (error) {}
    } else {
    }
  }
};
const queryURLParams = (URL) => {
  let url = URL.split("?")[1];
  const urlSearchParams = new URLSearchParams(url);
  const params = Object.fromEntries(urlSearchParams.entries());
  return params;
};

const getCode = () => {
  //没授权先授权,授权后会有一个code在地址栏上
  let params = queryURLParams(window.location.href);
  if (params.code) {
    let _code = localStorage.getItem("code");
    // console.log(_code != params.code, '996')
    if (_code != params.code) {
      localStorage.setItem("code", params.code);
      getOpenidFn();
    }
    return;
  }
  // return
  window.location.href =
    "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
    appid +
    "&redirect_uri=" +
    encodeURIComponent(window.location.href) +
    "&response_type=code&connect_redirect=1&scope=snsapi_base&state=state#wechat_redirect";
};

// 微信环境获取code
if (is_weixn()) {
  getCode();
  initWeixinJSBridge();
}

let amount = ref(0);
let imageList = ref([]);
const GetGoodsDetail = async () => {
  let { data } = await GoodsDetail({ goodsId: route.query.goodsId });
  amount.value = data.unitPrice * 100;
  imageList.value = data.image;
  state.Img01 = data.avatar;
};

onMounted(() => {
  state.anchorType[0].image = route.query.qrCode;
  state.anchorType[0].money = Number(route.query.diyPrice);
  // state.isWeixin = is_weixn()
  GetGoodsDetail();
});
</script>



<style lang="scss" scoped>
.index-container {
  width: 100vw;
  height: 100vh;
  background: #f2f2f2;
  box-sizing: border-box;
}

.goods-detail-box {
  background: #fff;
  padding: 30px 10px 10px 10px;
  display: flex;
  justify-content: center;
  .van-image {
    display: block;
    margin: 0 auto;
  }
  .goods-detail {
    color: #333;
    text-align: center;
    h3 {
      padding-top: 10px;
      font-size: 20px;
      font-weight: normal;
    }

    p {
      color: #f00;
      font-size: 20px;
      // margin-top: 10px;
      &::before {
        content: "￥";
        font-size: 14px;
        margin-right: 2px;
        color: #f00;
      }
    }
  }
}

.weixin-open {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(222, 222, 222);
  z-index: 999;
  display: flex;
  justify-content: center;
  align-items: flex-start;

  img {
    width: 100%;
  }
}

.pay-btn {
  margin-top: 30px;

  .pay-item {
    display: flex;
    align-items: center;
    justify-content: flex-start;
  }

  img {
    width: 24px;
    height: 24px;
    margin-right: 10px;
  }
}

:deep(.van-cell-group--inset) {
  margin: 0;
}

.verify-pay-btn {
  width: calc(100% - 30px);
  padding: 15px;
  position: absolute;
  bottom: 0;

  :deep(.van-button) {
    width: 100%;
  }
}

.tips {
  color: #fff;

  img {
    width: 100%;
  }
}

.pay-wx-main {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;

  .pay-item {
    // padding:15px;
    border-radius: 8px;
    overflow: hidden;

    h5 {
      font-size: 18px;
      margin-bottom: 10px;
    }

    img {
      width: 100%;
    }

    h5,
    p {
      text-align: center;
    }

    p {
      padding-bottom: 20px;
    }
  }
}
.default-browser {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 99999;
  background: #fff;
  img {
    width: 100%;
  }
}
.image-list {
  padding: 5px;
  .img-item {
    .van-image {
      width: 100%;
      height: 80px;
    }
  }
}
.img-item-more {
  font-size: 40px;
  text-align: center;
  line-height: 80px;
}

.wx-index-container {
  padding-top: 0 !important;
}
</style>
